package com.cy.jt.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 说明: 学框架就是学规则,规范
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!"jack".equals(username)) throw new UsernameNotFoundException("user not exists");

        //数据库查询的密码,权限
        String encodePWD = bCryptPasswordEncoder.encode("123");
        List<GrantedAuthority> authorities =
                AuthorityUtils.commaSeparatedStringToAuthorityList("AA,BB,CC");
        User user = new User(username,encodePWD,authorities);
        //源码 : public class User implements UserDetails, CredentialsContainer {
        //User实现了UserDetails -- 多态
        return user;
    }
}
